import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/index.vue'
import Layout from '@/views/Layout'
import Home from '@/views/Home'
import User from '@/views/User'
import Search from '@/views/Search'
import SearchResult from '@/views/Search/SearchResult'
// import ArticleDetail from '@/views/ArticleDetail'
// import UserEditor from '@/views/User/UserEdit.vue'
// import Chat from '@/views/Chat'
// import store from '@/store/index.js'
Vue.use(VueRouter)

const routes = [
  {
    path: '/chat',
    component: () => import('@/views/Chat')
  },
  {
    path: '/user-editor',
    component: () => import('@/views/User/UserEdit.vue')
  },
  {
    path: '/article/:aid',
    component: () => import('@/views/ArticleDetail')
  },
  {
    path: '/search/:keywords',
    component: SearchResult
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/layout',
    component: Layout,
    redirect: '/layout/home',
    children: [
      {
        path: 'home',
        component: Home,
        meta: { // 给当前路由对象添加额外信息
          isR: true,
          top: 0
        }
      },
      {
        path: 'user',
        component: User
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  if (to.path !== '/login') {
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      next(false)
    }
  } else {
    next()
  }
})
router.afterEach((to, from) => {
  setTimeout(() => {
    window.scrollTo(0, to.meta.top)
  })
})
export default router
